package com.mvp.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.StringRes;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.webkit.WebView;

import com.mvp.BuildConfig;
import com.mvp.dagger.components.ApplicationComponent;
import com.mvp.dagger.components.DaggerApplicationComponent;
import com.mvp.dagger.modules.ApplicationModule;
import com.mvp.event.TaokouEvent;
import com.mvp.utils.SharedPreferencesUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.LinkedList;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import timber.log.Timber;

import static java.lang.String.format;
import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2018/9/11.
 */
public class BaseApplication extends Application implements ApplicationInter {

    public static Application sApplication;
    public static Context sContext;

    //一键退出App
    // 此处采用 LinkedList作为容器，增删速度快
    private String TAG = "activityLinkedList APP 容器==";
    public final static LinkedList<Activity> activityLinkedList = new LinkedList<>();

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    protected static ApplicationComponent applicationComponent;

    @Override
    public void onCreate() {
        super.onCreate();

        sContext = getApplicationContext();
        sApplication = this;


        //todo Using WebView from more than one process at once with the same data directory is not supported. http
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            String processName = getProcessName(this);
            if (!TextUtils.equals("com.wushi.lenovo.asia5b", processName)) {////判断不等于默认进程名称
                WebView.setDataDirectorySuffix(processName);
            }
        }

        initDagger();

        //初始化sharepreferences
        SharedPreferencesUtils.initSharedPreferences(this);

        initTimber();

        //activity生命周期监视  一键退出App
        activityLifecycleForExitApp();
    }

    public String getProcessName(Context context) {
        if (context == null) return null;
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == android.os.Process.myPid()) {
                return processInfo.processName;
            }
        }
        return null;
    }

    private void initTimber() {
        if (BuildConfig.DEBUG || true) {
            Timber.plant(new Timber.DebugTree());
        } else {
//            Timber.plant(new CrashlyticsTree());
        }
    }

    private void initDagger() {
        applicationComponent = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this))
                .build();
        applicationComponent.inject(this);
    }

    public static ApplicationComponent getApplicationComponent() {
        return applicationComponent;
    }


    //activity生命周期监视  一键退出App
    private void activityLifecycleForExitApp() {
        //一键退出App
        //步骤1：在BaseApplication类的子类里建立Activity链表
        //缺点：需要 Activity 经历正常的生命周期，即创建时调用onCreate（），结束时调用onDestroy（）
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                d(format("--->>>>>>>>---onActivityCreated:%s", activity.getLocalClassName()));
                activityLinkedList.add(activity);
                // 在Activity启动时（onCreate()） 写入Activity实例到容器内
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                d(format("--->>>>>>>>---onActivityDestroyed:%s", activity.getLocalClassName()));
                activityLinkedList.remove(activity);
                // 在Activity结束时（Destroyed（）） 写出Activity实例
            }

            @Override
            public void onActivityStarted(Activity activity) {
                d(format("--->>>>>>>>---onActivityStarted:%s", activity.getLocalClassName()));
            }

            @Override
            public void onActivityResumed(Activity activity) {
                d(format("--->>>>>>>>---onActivityResumed:%s", activity.getLocalClassName()));
                //安卓10.0以上不可以继续后台监听剪切板
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
                    parseCm();
                }
            }

            @Override
            public void onActivityPaused(Activity activity) {
                d(format("--->>>>>>>>---onActivityPaused:%s", activity.getLocalClassName()));
            }

            @Override
            public void onActivityStopped(Activity activity) {
                d(format("--->>>>>>>>---onActivityStopped:%s", activity.getLocalClassName()));
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }
        });
    }

    private static long lastGetCopyContentTime = 0;//防止监听剪切板两次

    public static void parseCm() {
        if ((System.currentTimeMillis() - lastGetCopyContentTime) < 3000) {
            return;
        }
        lastGetCopyContentTime = System.currentTimeMillis();
        ClipboardManager cm = (ClipboardManager) sContext.getSystemService(Context.CLIPBOARD_SERVICE);
        Observable.just(cm)
                .map(new Function<ClipboardManager, String>() {
                    @Override
                    public String apply(ClipboardManager clipboardManager) throws Exception {
                        String url = "";
                        if (cm.hasPrimaryClip() && cm.getPrimaryClip().getItemCount() > 0) {
                            ClipData primaryClip = cm.getPrimaryClip();
                            if (primaryClip.getDescription() != null && TextUtils.equals("wsy", primaryClip.getDescription().getLabel())) {
                                d(format("淘口令1--->>>>>>>>---监听标记wsy"));
                                return url;
                            }
                            ClipData.Item item = cm.getPrimaryClip().getItemAt(0);
                            if (item != null) {
                                if (!TextUtils.isEmpty(item.getText())) {
                                    url = item.getText().toString();
                                }
                            }

                        }
                        if (TextUtils.isEmpty(url)) {
                            return "";
                        }
                        return url;
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(url -> {
                    d(format("淘口令1--->>>>>>>>---监听复制内容", url));
                    if (!TextUtils.isEmpty(url)) {
                        EventBus.getDefault().post(new TaokouEvent(url));
                        try {
                            d(format("淘口令1--->>>>>>>>---监听复制并添加标记wsy", url));
                            cm.setPrimaryClip(ClipData.newPlainText("wsy", url));
                        } catch (Exception e) {

                        }
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                });

    }

    // 退出Activity
    public static void finishActivity(Class<?> finishActivity) {
        // 退出Activity
        for (Activity activity : activityLinkedList) {
            if (activity.getClass().getSimpleName().equals(finishActivity.getSimpleName())) {
                activity.finish();
            }
        }
    }

    public static boolean hasActivity(Class<?> finishActivity) {
        for (Activity activity : activityLinkedList) {
            if (activity.getClass().getSimpleName().equals(finishActivity.getSimpleName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 为什么用这种方式?因为小米手机使用Application只能获取默认values的资源,暂时不知道解决办法,
     * 所以只能先用此方法
     *
     * @param id
     * @return
     */
    public static String getAppString(@StringRes int id) {
        if (activityLinkedList != null && activityLinkedList.size() > 0) {
            return activityLinkedList.get(activityLinkedList.size() - 1).getResources().getString(id);
        }
        return BaseApplication.sContext.getResources().getString(id);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        //内存不足尝试主动释放内存
        System.gc();
        System.runFinalization();
    }


    @Override
    public String getRegistrationId() {
        return "";
    }
}
